package com.zlll.winner.service.sysUser;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlll.winner.business.model.sysUser.SysUser;
import com.zlll.winner.business.model.sysUser.SysUserRole;
import com.zlll.winner.business.service.sysUser.ISysUserRoleService;
import com.zlll.winner.business.service.sysUser.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlll.winner.enums.CommonEnum;
import com.zlll.winner.mapper.sysUser.SysUserMapper;
import com.zlll.winner.mapper.sysUser.SysUserRoleMapper;
import com.zlll.winner.util.PasswordEncoder;
import com.zlll.winner.util.RegexMatcherUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ricky
 * @since 2019-08-23
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private ISysUserRoleService iSysUserRoleService;

    /**
     * 登录
     * @param userName
     * @param passWord
     * @return
     */
    @Transactional(readOnly = true)
    public SysUser login(String userName, String passWord)  {
        SysUser result = null;
        QueryWrapper<SysUser> query = new QueryWrapper<SysUser>();
        query.eq("is_del",CommonEnum.DelEnum.UNDEL.val());
        query.eq("user_name", userName);
        List<SysUser> userList = sysUserMapper.selectList(query);
        if (userList != null && userList.size() > 0) {
            SysUser user = userList.get(0);
            String encodePassWord = PasswordEncoder.encode(passWord,user.getSalt());
            Assert.isTrue(user.getPassword().equals(encodePassWord),"密码错误，请重试！");
            result = user;
        }
        return result;
    }

    /**
     * 获取用户列表信息
     * @param user
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public IPage<SysUser> findUserPage(SysUser user, Integer pageNo, Integer pageSize) {
        IPage<SysUser> page = new Page<SysUser>(pageNo,pageSize);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",CommonEnum.DelEnum.UNDEL.val());
        if(user.getUserName()!=null && !"".equals(user.getUserName())){
            queryWrapper.like("user_name",user.getUserName());
        }
        queryWrapper.orderBy(true,false,"create_time");
        return sysUserMapper.selectPage(page, queryWrapper);
    }

    /**
     * 新增用户
     * @param user
     * @param roleId
     * @param userId
     * @param name
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void addUser(SysUser user, Long roleId, Long userId, String name) {
        checkUser("add", user);
        user.setIsDel(CommonEnum.DelEnum.UNDEL.val());
        user.setCreateTime(new Date().getTime());
        user.setCreateUserId(userId);
        user.setCreateUser(name);
        user.setUserType(1);
        String salt = PasswordEncoder.genRandomNum();
        user.setSalt(salt);
        user.setPassword(PasswordEncoder.encode(user.getPassword(), salt));
        sysUserMapper.insert(user);
        Long newUserId = user.getId();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(newUserId);
        sysUserRole.setRoleId(roleId);
        sysUserRole.setIsDel(CommonEnum.DelEnum.UNDEL.val());
        sysUserRole.setCreateTime(new Date().getTime());
        sysUserRole.setCreateUserId(userId);
        sysUserRole.setCreateUser(name);
        sysUserRoleMapper.insert(sysUserRole);
    }

    /**
     * 更新用户信息
     * @param user
     * @param roleId
     * @param userId
     * @param name
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void updateUser(SysUser user, Long roleId, Long userId, String name) {
        checkUser("update", user);
        user.setUpdateUserId(userId);
        user.setUpdateTime(new Date().getTime());
        user.setUpdateUser(name);
        sysUserMapper.updateById(user);
        Long newUserId = user.getId();
        List<SysUserRole> list = iSysUserRoleService.getSysUserRoleByUserId(newUserId);
        if(list!=null && list.size()>0){
            SysUserRole sysUserRole = list.get(0);
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUpdateUserId(userId);
            sysUserRole.setUpdateTime(new Date().getTime());
            sysUserRole.setUpdateUser(name);
            sysUserRoleMapper.updateById(sysUserRole);
        }else{
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(newUserId);
            sysUserRole.setRoleId(roleId);
            sysUserRole.setIsDel(CommonEnum.DelEnum.UNDEL.val());
            sysUserRole.setCreateTime(System.currentTimeMillis());
            sysUserRole.setCreateUserId(userId);
            sysUserRole.setCreateUser(name);
            sysUserRole.setUpdateUserId(userId);
            sysUserRole.setUpdateTime(new Date().getTime());
            sysUserRole.setUpdateUser(name);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }

    /**
     * 删除用户信息
     * @param id
     * @param userId
     * @param name
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void deleteUser(Long id, Long userId, String name) {
        SysUser user = sysUserMapper.selectById(id);
        user.setIsDel(CommonEnum.DelEnum.DEL.val());
        user.setUpdateTime(new Date().getTime());
        user.setUpdateUserId(userId);
        user.setUpdateUser(name);
        sysUserMapper.updateById(user);
        List<SysUserRole> list = iSysUserRoleService.getSysUserRoleByUserId(id);
        if(list!=null && list.size()>0){
            list.forEach(sysUserRole -> {
                sysUserRole.setIsDel(CommonEnum.DelEnum.DEL.val());
                sysUserRole.setUpdateTime(new Date().getTime());
                sysUserRole.setUpdateUser(name);
                sysUserRole.setUpdateUserId(userId);
                sysUserRoleMapper.updateById(sysUserRole);
            });
        }
    }

    /**
     * 重置密码功能
     * @param ids
     * @param password
     * @param userId
     * @param name
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void resetPassword(Long[] ids, String password, Long userId, String name) {
        SysUser user;
        for(Long id : ids){
            user = new SysUser();
            user.setId(id);
            user.setPassword(password);
            String salt = PasswordEncoder.genRandomNum();
            user.setSalt(salt);
            user.setPassword(PasswordEncoder.encode(user.getPassword(), salt));
            user.setUpdateUserId(userId);
            user.setUpdateTime(new Date().getTime());
            user.setUpdateUser(name);
            sysUserMapper.updateById(user);
        }
    }

    /**
     * 判断用户是否新增重复账号
     * @param action
     * @param user
     */
    private void checkUser(String action, SysUser user) {
        String userName = user.getUserName();
        String mobile = user.getTelephone();
        if (RegexMatcherUtil.NotChinese.matcher(userName).find()) {
            Assert.isTrue(false,"登录账号不能为中文");
        }
        if (!RegexMatcherUtil.MobileNum.matcher(mobile).find()) {
            Assert.isTrue(false,"手机号不为11位数字组合");
        }
        SysUser userExample = new SysUser();
        userExample.setUserName(userName);
        userExample.setIsDel(CommonEnum.DelEnum.UNDEL.val());
        List<Long> ids = sysUserMapper.selectByCondition(userName);
        if (CollectionUtils.isNotEmpty(ids)) {
            if ("add".equals(action)) {
                Assert.isTrue(false,"账号已被重复使用");
            } else if ("update".equals(action)) {
                for (Long id : ids) {
                    if (id.longValue()!=user.getId().longValue()) {
                        Assert.isTrue(false,"账号已被重复使用");
                    }
                }
            }
        }
    }
}
